<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="授权IP" prop="licenseIp">
        <el-input
          v-model="queryParams.licenseIp"
          placeholder="请输入授权IP"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="license模式" prop="mode">
        <el-select v-model="queryParams.mode" placeholder="license模式" clearable size="small" style="width: 180px">
          <el-option
            v-for="dict in modeOptions"
            :key="dict.dictCode"
            :label="dict.dictLabel"
            :value="dict.dictCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="license状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="license状态" clearable size="small" style="width: 180px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictCode"
            :label="dict.dictLabel"
            :value="dict.dictCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增license</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改license</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除license</el-button>
      </el-col>
      <el-col :span="1.5" style="float: right" v-if="dynamicColumnSetting">
        <el-popover
          placement="bottom"
          min-width="80"
          trigger="click"
          popper-class="col-setting-popover"
        >
          <el-button
            slot="reference"
            type="primary"
            icon="el-icon-setting"
            size="mini"
          >筛选</el-button>
          <div class="col-setting-title">显示设置</div>
          <el-checkbox-group v-model="visibleIndexs" :min="0" class="col-setting-group">
            <el-checkbox
              v-for="colInfo in columnInfos"
              :label="colInfo.index"
              :key="colInfo.index"
              :disabled="colInfo.disabled"
              v-show="!colInfo.disabled || showAlwaysShowColumnInCheckbox"
            >{{ colInfo.label }}</el-checkbox>
          </el-checkbox-group>
        </el-popover>
      </el-col>
    </el-row>

    <el-table ref="pageTable" class="loading-area" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="columnVisibles[0]"/>
      <el-table-column label="客户名称" align="center" prop="consumerName" v-if="columnVisibles[1]"/>
      <el-table-column label="联系电话" align="center" prop="consumerCellphone" v-if="columnVisibles[2]"/>
      <el-table-column label="授权Ip" align="center" prop="licenseIp" v-if="columnVisibles[3]"/>
      <el-table-column label="授权码" align="center" prop="licenseCode" v-if="columnVisibles[4]"/>
      <el-table-column label="license模式" align="center" prop="mode" :formatter="modeFormat" v-if="columnVisibles[5]"/>
      <el-table-column label="license有效期" align="center" prop="expiryTime" v-if="columnVisibles[6]"/>
      <el-table-column label="license公钥" align="center" prop="licensePublicKey" v-if="columnVisibles[7]"/>
      <el-table-column label="license私钥" align="center" prop="licensePrivateKey" v-if="columnVisibles[8]"/>
      <el-table-column label="私钥种子" align="center" prop="seed" v-if="columnVisibles[9]"/>
      <el-table-column label="license证书内容" align="center" prop="licenseContent" v-if="columnVisibles[10]"/>
      <el-table-column label="license状态" align="center" prop="status" :formatter="statusFormat" v-if="columnVisibles[11]"/>
      <el-table-column label="通知邮箱" align="center" prop="notifyEmail" v-if="columnVisibles[12]"/>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columnVisibles[13]"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" v-if="columnVisibles[14]"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >下载license证书</el-button>
          <!--                    <el-button
                                      size="mini"
                                      type="text"
                                      icon="el-icon-delete"
                                      @click="handleDelete(scope.row)"
                              >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="consumerName">
              <el-input v-model="form.consumerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户手机号码" prop="consumerCellphone">
              <el-input v-model="form.consumerCellphone" placeholder="请输入客户手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="到期通知邮箱" prop="notifyEmail">
              <el-input v-model="form.notifyEmail" placeholder="请输入到期发送通知邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="授权IP" prop="licenseIp">
              <el-input v-model="form.licenseIp" placeholder="请输入要授权IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="license模式" prop="mode">
              <el-radio-group v-model="form.mode">
                <el-radio
                  v-for="dict in modeOptions"
                  :key="dict.dictCode"
                  :label="dict.dictCode"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="授权有效期" prop="expiryTime">
              <el-date-picker type="datetime" v-model="form.expiryTime" format="yyyy-MM-dd HH:mm:ss"
                              value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择授权有效期" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="license状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictCode"
                  :label="dict.dictCode"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import { download } from "@/utils/commonUtil";
import { list, get, add, update,remove} from "@/api/comm/license";
export default {
  name: "license",
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 状态数据字典
      statusOptions: [],
      //授权模式数据字典
      modeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        licenseIp: undefined,
        mode: undefined,
        expiryTime: undefined,
        status: undefined,
      },
      columnInfos: [], // 所有列信息
      showAlwaysShowColumnInCheckbox: true,
      dynamicColumnSetting: true,
      columnVisibles: new Array(15).fill(true),//设置列可见性
      visibleIndexs: [], // 可见列的下标集合
      alwaysShowColumnIndexs: [1,3,5],//总是显示的列的下标（不可隐藏的列）,列下标从 0 开始
      hidenColumnIndexs: [0,2,4,7,8,9,10],//隐藏列的下标集合
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        consumerName: [
          {required: true, message: "请输入客户名称", trigger: "blur"}
        ],
        notifyEmail: [
          {required: true, message: "请输入接收通知的邮箱", trigger: "blur"}
        ],
        licenseIp: [
          {required: true, message: "请输入授权IP", trigger: "blur"}
        ],
        mode: [
          {required: true, message: "请选择license模式", trigger: "blur"}
        ],
        expiryTime: [
          {required: true, message: "请选择授权有效期", trigger: "blur"}
        ],
        status: [
          {required: true, message: "请选择证书状态", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("licenseStatus").then(res => {
      this.statusOptions = [];
      res.data.forEach((dict)=>{
        let tmpDict = {};
        tmpDict.dictCode = Number(dict.dictCode);//数据类型转换，el-select数据回显数据类型必须要一致
        tmpDict.dictLabel = dict.dictLabel;
        this.statusOptions.push(tmpDict);
      });
    });
    this.getDicts("licenseMode").then(res => {
      this.modeOptions = [];
      res.data.forEach((dict)=>{
        let tmpDict = {};
        tmpDict.dictCode = Number(dict.dictCode);//数据类型转换，el-select数据回显数据类型必须要一致
        tmpDict.dictLabel = dict.dictLabel;
        this.modeOptions.push(tmpDict);
      });
    });
  },
  methods: {
    /** 查询列表 */
    getList() {
      list(this.queryParams).then(response => {
        this.dataList = response.data.rows;
        this.total = response.data.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        consumerName: undefined,
        consumerCellphone: undefined,
        notifyEmail: undefined,
        licenseIp: undefined,
        mode: 0,
        expiryTime: undefined,
        status: 0,
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      get(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      const fileUrl = row.licenseFileUrl;
      const fileName = row.licenseCode+"_"+row.mode+'_appLicense.lic';
      download(fileUrl, fileName);
    },
    // 状态字典翻译
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 模式字典翻译
    modeFormat(row) {
      return this.selectDictLabel(this.modeOptions, row.mode);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            update(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            add(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除ID为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return remove(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },


    oprColumns(indexs, isShow) {
      let self = this;
      indexs.forEach(index => {
        self.$set(self.columnVisibles, index, isShow);
      });
    }
  },
  mounted() {

    let self = this;
    if (self.$refs.pageTable.$slots.default) {
      let columnIndex = 0;
      self.$refs.pageTable.$slots.default.forEach((columnIns, index) => {
        if (columnIns.componentOptions === undefined) {
          return;
        }
        let props = columnIns.componentOptions.propsData;
        if (
          props.prop === undefined ||
          props.type === "selection" ||
          props.type === "index"
        ) {
          return;
        }
        // 保存所有列的信息
        let label = props.label
        let colName = props.prop
        self.columnInfos.push({
          label: label,
          colName: colName,
          index: columnIndex,
          disabled: false
        })
        // 记录初始展示的列的下标
        if (self.hidenColumnIndexs.indexOf(columnIndex) === -1) {
          self.visibleIndexs.push(columnIndex);
        }
        columnIndex++
      })
      // 处理总是显示的列（不可隐藏的列）
      self.alwaysShowColumnIndexs.forEach(
        index => (self.columnInfos[index].disabled = true)
      );
      // 处理初始隐藏的列
      self.oprColumns(self.hidenColumnIndexs, false);
    }

  },
  beforeUpdate() {
    let self = this;
    self.$nextTick(_ => {
      self.$refs.pageTable.doLayout();
    });
  },
  watch: {
    visibleIndexs(newValue, oldValue) {
      let self = this;
      let willHideIndexs = [], willShowIndexs = [];
      willShowIndexs = newValue.filter(index => {
        return oldValue.indexOf(index) === -1;
      });
      willHideIndexs = oldValue.filter(index => {
        return newValue.indexOf(index) === -1;
      });
      self.oprColumns(willShowIndexs, true);
      self.oprColumns(willHideIndexs, false);
    }
  }
}
</script>
